document.addEventListener('DOMContentLoaded', function() {
	createGrid();
});

function createGrid() {
	const grid = document.getElementById('sudokuGrid');
	for (let row = 0; row < 9; row++) {
		for (let col = 0; col < 9; col++) {
			let cell = document.createElement('div');
			cell.className = 'sudoku-cell';

			let input = document.createElement('input');
			input.type = 'text';
			input.maxLength = 1;
			input.pattern = '[1-9]'; // 确保只能输入1到9的数字
			input.className = 'sudoku-input';
			input.id = 'cell-' + row + '-' + col; // 设置唯一的ID

			cell.appendChild(input);
			grid.appendChild(cell);
		}
	}
}



function solveSudoku() {
	let grid = [];
	for (let row = 0; row < 9; row++) {
		grid[row] = [];
		for (let col = 0; col < 9; col++) {
			let cell = document.getElementById('cell-' + row + '-' + col);
			grid[row][col] = cell.value ? parseInt(cell.value) : 0;
		}
	}

	if (solve(grid, 0)) {
		for (let row = 0; row < 9; row++) {
			for (let col = 0; col < 9; col++) {
				document.getElementById('cell-' + row + '-' + col).value = grid[row][col];
			}
		}
	} else {
		alert("无法解决此数独！");
	}
}

function solve(grid, index) {
	if (index === 81) {
		return true;
	}

	let row = Math.floor(index / 9);
	let col = index % 9;

	if (grid[row][col] !== 0) {
		return solve(grid, index + 1);
	}

	for (let num = 1; num <= 9; num++) {
		if (isValid(grid, row, col, num)) {
			grid[row][col] = num;
			if (solve(grid, index + 1)) {
				return true;
			}
			grid[row][col] = 0;
		}
	}
	return false;
}

function isValid(grid, row, col, num) {
	for (let i = 0; i < 9; i++) {
		if (grid[row][i] === num || grid[i][col] === num || grid[3 * Math.floor(row / 3) + Math.floor(i / 3)][3 * Math
				.floor(col / 3) + i % 3
			] === num) {
			return false;
		}
	}
	return true;
}

function generateSudoku() {
	clearSudoku();

	// 初始化空的数独解决方案
	let solution = [];
	for (let i = 0; i < 9; i++) {
		solution.push(Array(9).fill(0));
	}

	// 在数独的随机位置填入一些初始数字
	for (let i = 0; i < 9; i++) {
		let row = Math.floor(Math.random() * 9);
		let col = Math.floor(Math.random() * 9);
		let num = Math.floor(Math.random() * 9) + 1;
		if (isValid(solution, row, col, num)) {
			solution[row][col] = num;
		}
	}

	// 使用 solve 函数完成数独解决方案
	if (!solve(solution, 0)) {
		console.error("Failed to generate a valid Sudoku puzzle.");
		return;
	}

	// 随机选择一些单元格显示数字
	let shownCount = 30; // 显示的数字数量
	for (let i = 0; i < shownCount; i++) {
		let row = Math.floor(Math.random() * 9);
		let col = Math.floor(Math.random() * 9);
		let cellId = 'cell-' + row + '-' + col;
		let cell = document.getElementById(cellId);
		if (cell && cell.value === "") {
			cell.value = solution[row][col];
		} else {
			i--; // 如果选中的单元格已经有数字，则重新选择
		}
	}
}

function clearSudoku() {
	for (let row = 0; row < 9; row++) {
		for (let col = 0; col < 9; col++) {
			document.getElementById('cell-' + row + '-' + col).value = '';
		}
	}
}
